#include "CustomToolButton.h"

CustomToolButton::CustomToolButton(QString name, QString data_f, QByteArray data):name(name),data_f(data_f),data(data)
{
	this->setText(name);
	if (data_f == "hex" || data_f == "hup_text" || data_f == "hup_hex" ) {
		this->setToolTip(data_f + ": " + data.toHex());
	}
	else {
		this->setToolTip(data_f + ": " + data);
	}
	
	this->setMinimumSize(QSize(120, 60));
	this->setPopupMode(QToolButton::MenuButtonPopup);

	QMenu* menu = new QMenu(this);
	QAction* menu_setting = new QAction(menu);
	QAction* menu_delete = new QAction(menu);
	menu_setting->setText("setting");
	menu_delete->setText("delete");
	menu->addAction(menu_setting);
	menu->addAction(menu_delete);
	this->setMenu(menu);

	connect(menu_setting, &QAction::triggered, this, [=]() {
		CmdSettingDialogSingleton::getInstance().initValue(this->name, this->data_f, this->data);
		CmdSettingDialogSingleton::getInstance().show();
		disconnect(&CmdSettingDialogSingleton::getInstance(), &CmdSettingDialogSingleton::cmd_setting_finished_signal, nullptr, nullptr);
		connect(&CmdSettingDialogSingleton::getInstance(), &CmdSettingDialogSingleton::cmd_setting_finished_signal, this,
			[=](QString name, QString data_f, QByteArray data) {
				this->name = name;
				this->data_f = data_f;
				this->data = data;

				this->setText(this->name);
				if (data_f == "hex" || data_f == "hup_text" || data_f == "hup_hex") {
					this->setToolTip(data_f + ": " + data.toHex());
				}
				else{
					this->setToolTip(data_f + ": " + data);
				}
				QMessageBox::information(this, "cmd", "cmd have been changed successful");
		});
	});
	connect(menu_delete, &QAction::triggered, this, [=]() {
		Cmd_Data cmd_data;
		cmd_data.name = name.toStdString();
		cmd_data.data_f = data_f.toStdString();
		cmd_data.data = data.toHex().toStdString();
		cout << "in menu_delete:" << cmd_data.name << ":" << cmd_data.data_f << ":" << cmd_data.data << ":" << endl;
		CmdJsonManager::deleteCmd(cmd_data);
		CmdJsonManager::dump();
		emit delete_signal();
		});

}

QByteArray CustomToolButton::getData()
{
	return data;
}
